package com.westar.tv;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.westar.tv.http.AppClient;
import com.westar.tv.utils.FilesUtils;
import com.westar.tv.utils.InstallationAPKUtil;
import com.westar.tv.utils.NetUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import cz.msebera.android.httpclient.Header;
import rx.Subscriber;

public class UpdateManager {

    //上下文
    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;

    private MaterialDialog mDownloadDialog;
    // 已下载大小
    TextView tv_downSize;
    // 总大小
    TextView tv_allSize;
    String allSizeStr;

    private AsyncHttpClient client;

    private RequestHandle requestHandle;

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 检查更新
     */
    public void checkUpdate() {
        if (NetUtils.isConnected(mContext)) {

            Subscriber<Version> subscriber = new Subscriber<Version>() {

                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    Toast.makeText(mContext, R.string.toast_soft_update_error, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(mContext, MainActivity.class);
                    mContext.startActivity(intent);
                    if (mContext instanceof WelcomeActivity) {
                        WelcomeActivity activity = (WelcomeActivity) mContext;
                        activity.finish();
                    }
                }

                @Override
                public void onNext(Version version) {
                    if (version != null) {
                        int versionCode = getVersionCode(mContext);
                        int serviceCode = version.getVersionCode();
                        if (serviceCode > versionCode) {//有更新,则进行更新
                            // 显示下载对话框
                            showDownloadDialog(version);
                        } else {//无更新进入主界面
                            Intent intent = new Intent(mContext, MainActivity.class);
                            mContext.startActivity(intent);
                            if (mContext instanceof WelcomeActivity) {
                                WelcomeActivity activity = (WelcomeActivity) mContext;
                                activity.finish();
                            }
                        }
                    }
                }
            };
            AppClient client = AppClient.getInstance();
            client.checkVersion(subscriber, Config.TYPENAME);
        } else {//网络未连接
            Toast.makeText(mContext, R.string.dialog_title_net_unconnected, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog(Version version) {
        // 构造软件下载对话框
        MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext)
                .title(R.string.soft_updating)
                .canceledOnTouchOutside(false)
                .customView(R.layout.dialog_update_progress, false);
        mDownloadDialog = builder.build();
        mDownloadDialog.show();
        View v = mDownloadDialog.getCustomView();
        mProgress = (ProgressBar) v.findViewById(R.id.download_progress);
        tv_downSize = (TextView) v.findViewById(R.id.down_size);
        tv_allSize = (TextView) v.findViewById(R.id.all_size);
        allSizeStr = mContext.getResources().getString(R.string.file_all_size);
        downloadApk(version);
    }

    /**
     * 下载apk文件
     */
    private void downloadApk(final Version version) {
        client = new AsyncHttpClient();
        requestHandle = client.get(version.getDownloadURL(), new FileAsyncHttpResponseHandler(mContext) {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                mDownloadDialog.dismiss();
                Toast.makeText(mContext, R.string.toast_soft_update_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File responseFile) {
                try {
                    // 获得存储卡的路径
                    String downPath = FilesUtils.getFileStorageDirectory();
                    //获取文件夹  防止有些手机不能自动创建文件夹
                    File apkFileDir = new File(downPath);
                    if (!apkFileDir.exists()) {
                        apkFileDir.mkdirs();
                    }
                    File apkFile = new File(apkFileDir, version.getVersionCode() + ".apk");
                    copyFile(responseFile, apkFile);
                    mDownloadDialog.dismiss();
                    //设置安装包的路径地址
                    CustomApplication.installationAPKPath = apkFile.getAbsolutePath();
                    //安装apk
                    InstallationAPKUtil.installationAPK(mContext, apkFile);
//                    if (mContext instanceof WelcomeActivity) {
//                        WelcomeActivity activity = (WelcomeActivity) mContext;
//                        activity.finish();
//                    }
                } catch (Exception e) {
                    Log.e("UpdateManager", e.getMessage());
                }
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                double progress = (double) bytesWritten / (double) totalSize;
                mProgress.setProgress((int) ((progress) * 100));
                tv_downSize.setText(FilesUtils.getFileSize(bytesWritten));
                if (TextUtils.isEmpty(tv_allSize.getText())) {
                    tv_allSize.setText(Html.fromHtml(String.format(allSizeStr, FilesUtils.getFileSize(totalSize))));
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(mContext, R.string.toast_soft_update_cancel, Toast.LENGTH_SHORT).show();
            }
        });
    }


    private void copyFile(File sourceFile, File targetFile) throws IOException {
        // 新建文件输入流并对它进行缓冲
        FileInputStream input = new FileInputStream(sourceFile);
        BufferedInputStream inBuff = new BufferedInputStream(input);

        // 新建文件输出流并对它进行缓冲
        FileOutputStream output = new FileOutputStream(targetFile);
        BufferedOutputStream outBuff = new BufferedOutputStream(output);

        // 缓冲数组
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }
        // 刷新此缓冲的输出流
        outBuff.flush();
        //关闭流
        inBuff.close();
        outBuff.close();
        output.close();
        input.close();
    }

}
